import React, { Component } from 'react';
import { Dialog, Button, Form, Input, Field, TreeSelect } from '@alifd/next';
import { orgs } from '../../../../api/Org';
import { Forest } from '../../../../libs/Tree';

const FormItem = Form.Item;

export default class EditDialog extends Component {
  static displayName = 'EditDialog';

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      dataIndex: null,
    };
    this.field = new Field(this);
  }
 componentWillMount() {
   const record = this.props.record;
   this.oth_fields = {
    useable: record.useable === null ? 0 : record.useable,
  };
 }

 dataToTree= (dataSource) => {
  const forest = new Forest();
  dataSource.forEach((menu) => {
      forest.init({
        label: menu.name,
        key: menu.id,
        pid: menu.parentId,
        id: menu.id,
        value: menu.id,
        children: [],
      });
  });
  return forest.roots;
}

  handleSubmit = () => {
    this.field.validate((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      const { dataIndex } = this.state;
      values.departmentId = this.oth_fields.departmentId;
      values.organizationId = this.oth_fields.organizationId;
      this.props.getFormValues(dataIndex, values);
      this.setState({
        visible: false,
      });
    });
  };

  onOpen = (index, record) => {
    orgs().then((response) => {
      const keys = Object.keys(record);
      keys.forEach((key) => {
        if (record[key] === null){
          record[key] = undefined;
        }
      });
      this.field.setValues({ ...record });
      const data = response.data.data;
      const roots = this.dataToTree(data);
      roots.forEach((ele) => {
        ele.selectable = (ele.type == '0');
      });
      this.setState({
        visible: true,
        dataIndex: index,
        dataSource: data,
        orgTree: roots,
      });
    });
  };

  handleChange =(value) => {
    this.oth_fields.departmentId = value;
    this.state.dataSource.forEach((ele) => {
      if (ele.id == value) {
        const pids = ele.parentIds.split(',');
       for (let i = 0; i < pids.length; i++) {
         const item = pids[i];
         if (item.length > 0){
          this.oth_fields.organizationId = item;
          break;
        }
       }
      }
    });
  }

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onUseableChange = (checked) => {
      this.oth_fields.useable = (checked === true ? 1 : 0);
  }

  checkPwd = (rule, value, callback) => {
    if (value !== this.field.getValue('password')){
      callback('密码不一致');
    } else {
      callback();
    }
  }
  render() {
    const init = this.field.init;
    const { index, record } = this.props;
    const formItemLayout = {
      labelCol: {
        fixedSpan: 6,
      },
      wrapperCol: {
        span: 14,
      },
    };

    const pwdType = 'password';
    return (
      <div style={styles.editDialog}>
        <Button type="primary" size="small" onClick={() => this.onOpen(index, record)}>
        编辑
        </Button>
        <Dialog
          style={{ width: 640 }}
          visible={this.state.visible}
          onOk={this.handleSubmit}
          closeable="esc,mask,close"
          onCancel={this.onClose}
          onClose={this.onClose}
          title="编辑"
        >
          <Form field={this.field}>
            <FormItem label="用户名称：" >
              <Input
                {...init('name', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              />
            </FormItem>

            <FormItem label="用户登录名：" >
              <Input
                {...init('loginName', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              />
            </FormItem>
            <FormItem label="重置密码：" >
              <Input htmlType={pwdType}
                {...init('password', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              />
            </FormItem>
            <FormItem label="重复密码：" >
              <Input htmlType={pwdType}
                {...init('repassword', {
                  rules: [
                    { required: true, message: '必填选项' },
                    { validator: this.checkPwd },
                  ],
                })}
              />
            </FormItem>
            <FormItem label="用户工号：" >
              <Input
                {...init('userNo')}
              />
            </FormItem>

            <FormItem label="用户手机：" >
              <Input
                {...init('mobile')}
              />
            </FormItem>
            <FormItem label="用户email：" >
              <Input
                {...init('email')}
              />
            </FormItem>

            <FormItem label="所属部门：" {...formItemLayout}>
              <TreeSelect 
                treeDefaultExpandAll 
                multiple={false}
                dataSource={this.state.orgTree} 
                onChange={this.handleChange} 
                style={{ width: 220 }} 
              />
            </FormItem>
          </Form>
        </Dialog>
      </div>
    );
  }
}

const styles = {
  editDialog: {
    display: 'inline-block',
    marginRight: '5px',
  },
};
